package keter.sec.springsec.security.handler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;


public class AjaxFailureHandler implements AuthenticationFailureHandler {
    /**
     * Logger for this class
     */
    private static final Logger logger = LoggerFactory.getLogger(AjaxFailureHandler.class);

    @Override
    public void onAuthenticationFailure(HttpServletRequest arg0, HttpServletResponse response, AuthenticationException ex)
            throws IOException, ServletException {
        PrintWriter out = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        try {
            out = response.getWriter();
            if (ex instanceof BadCredentialsException) {
                out.append("{code:1,message:\"用户名或密码错误\"}");
            } else if (ex instanceof LockedException) {
                out.append("{code:2,message:\"用户被锁定\"}");
            } else {
                out.append("{code:\"99\",message:" + ex.getMessage() + "}");
            }
        } catch (IOException e) {
            logger.error("向前台返回user对象失败", e);
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }
}


